<template>
  <div class="app-container">

      <el-form class="main-form" v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true" >
         <el-form-item label="商品分类" prop="category">
            <el-select class="category-first" v-model="queryParams.firstCategory" placeholder="一级类目" filterable clearable style="width: 200px" @change="handleQuery">
               <el-option
                  v-for="(option, idx) in categories"
                  :key="idx"
                  :label="option.name"
                  :value="option.id"
               />
            </el-select>
            <el-select class="category-second" v-if="queryParams.firstCategory" v-model="queryParams.secondCategory" filterable placeholder="二级类目" clearable style="width: 200px" @change="handleQuery">
               <el-option
                  v-for="(option, idx) in categories.filter(item => item.id === queryParams.firstCategory)[0].children"
                  :key="idx"
                  :label="option.name"
                  :value="option.id"
               />
            </el-select>
         </el-form-item>


         <!-- <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item> -->
      </el-form>





      <el-table class="data-list" v-loading="loading" :data="records">
         <el-table-column v-for="(fieldLabel) in fieldLabels" :label="fieldLabel" align="center" :prop="fieldLabel">
            <template #default="scope">
              <template v-if="fieldLabel.endsWith('日期')">
                {{ $filters.date(scope.row[fieldLabel], 'yyyy-MM-dd') }}
              </template>
              <template v-else-if="fieldLabel.endsWith('佣金') && scope.row[fieldLabel]">
                {{ Math.floor(scope.row[fieldLabel] * 100) }} %
              </template>
              <template v-else>
                {{ scope.row[fieldLabel] }}
              </template>

            </template>
         </el-table-column>

      </el-table>




   </div>
</template>
<script setup lang="ts">
import {reactive, ref, toRefs, onMounted } from 'vue'
import * as selectionService from '@/api/service/SelectionService'
import * as categoryService from '@/api/service/CategoryService'


defineOptions({ name: "Selection" });

const globalVal = globalThis as any
const fieldLabels = ref<string[]>([])
const records = ref<any>([])
const loading = ref(false)
const showSearch = ref(true)
const categories = ref<any>([])



const data = reactive({
  form: {},
  queryParams: {
    firstCategory: undefined,
    secondCategory: undefined,
    createBy: undefined,
    status: undefined
  }
});

const { queryParams } = toRefs(data)

/** 查询列表 */
async function findList() : Promise<any> {
  //loading.value = true;
  let list = [];
  let labels:string[] = [];
  const conditions:any[] = <any>[];

  if(data.queryParams.firstCategory){
    conditions.push({
      field_name: categoryService.FIRST_CATEGORY,
      operator: 'is',
      value: [data.queryParams.firstCategory]
    })
  }

  if(data.queryParams.secondCategory){
    conditions.push({
      field_name: categoryService.SECOND_CATEGORY,
      operator: 'is',
      value: [data.queryParams.secondCategory]
    })
  }


  const queryBody = {
    filter: {
      conjunction:'and',
      conditions: conditions
    }
  }

  loading.value = true;
  for await (const page of await selectionService.findList(queryBody)){
    const items = page.items.map(item => {
      const result = globalVal.parseFeishuRecord(item);
      const keys = Object.keys(result);
      for(const key of keys){
        if(!labels.includes(key) && !['序号', 'recordId'].includes(key)){
          labels.push(key);
        }
      }
      return result;
    })
    list = list.concat(items)
    records.value = list;
    fieldLabels.value = labels;
    loading.value = false;
  }



}


/** 搜索按钮操作 */
function handleQuery(): void {
  findList()
}

/**
 * 加载分类信息
 */
async function loadCategories(): Promise<any>{
  categoryService.categories().then(items=>{
    categories.value = items;
  })

}


onMounted(() => {
  loadCategories();
  findList();

  // globalVal.electronApi.getCookies('https://syt.kwaixiaodian.com').then(resp =>{
  //   if(resp.success && resp.cookies.length > 0){
  //     systemService.save({
  //       '键':'cookie',
  //       '值':JSON.stringify(resp.cookies)
  //     }).then(res=>{
  //       console.log(res)
  //     })
  //   }

  // })

})

</script>

<style lang="scss" scoped>
.app-container{
  display: flex;
  flex-direction: column;
}
.app-tables{
  display: flex;
  align-items: center;
  h4{
    font-size: 14px;
    line-height: 14px;
    margin:0;
    padding: 0;
    margin-right: 40px;
    line-height: 36px;
    white-space: nowrap;

  }
  .table-item{
    margin-right: 20px;
    label{
      font-size: 14px;
      margin-right: 10px;
      line-height: 36px;
      font-weight: bold;
    }
  }

}
.main-form{



  .category-second{
    margin-left: 20px;
  }
}

.data-list{
  flex:1;
}
.generate-stats{
  font-weight: bold;
  text-align: right;
  line-height: 30px;
  .text-error{
    color: red;

  }

}
</style>
